import React, { useEffect, useState } from "react";
import FirstTitle from "@/components/FirstTitle";
import EffectContainer from "@/components/effectContainer";
import type { GetProp, UploadFile, UploadProps } from "antd";
import Code from "@/components/code";
import { Upload } from "antd";
import { getCode } from "@/api/codeApi.ts";

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

// 创建平铺水印
const createTiledWatermark = async (ctx, width, height) => {
  const text = "水印.....";
  const fontSize = Math.max(12, Math.min(width, height) / 20); // 比平铺水印稍大
  const padding = fontSize; // 边距
  const opacity = 0.8; // 提高一点透明度

  ctx.save();
  ctx.font = `bold ${fontSize}px Arial`;
  ctx.fillStyle = `rgba(255, 255, 255, ${opacity})`;
  ctx.fontSize = 24;
  ctx.textAlign = "left";
  ctx.textBaseline = "bottom";

  // 计算水印位置（左下角，带边距）
  const x = padding;
  const y = height - padding;

  ctx.fillText(text, x, y - fontSize * 0.1);

  ctx.restore();
};

// 添加水印函数
const addWatermark = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = (e: any) => {
      const img: any = new Image();
      img.onload = async () => {
        const canvas = document.createElement("canvas");
        const ctx: any = canvas.getContext("2d");

        // 设置canvas尺寸
        canvas.width = img.width;
        canvas.height = img.height;

        // 绘制原始图片
        ctx.drawImage(img, 0, 0);

        // 添加平铺水印
        await createTiledWatermark(ctx, canvas.width, canvas.height);

        // 转换为Blob
        canvas.toBlob(
          (blob) => {
            if (!blob) {
              reject(new Error("Canvas转换失败"));
              return;
            }

            const watermarkedFile = new File([blob], file.name, {
              type: file.type || "image/jpeg",
              lastModified: Date.now(),
            });
            resolve(watermarkedFile);
          },
          file.type || "image/jpeg",
          0.9,
        ); // 0.9表示JPEG质量
      };
      img.onerror = () => reject(new Error("图片加载失败"));
      img.src = e.target.result;
    };
    reader.onerror = () => reject(new Error("文件读取失败"));
    reader.readAsDataURL(file);
  });
};

function WaterMark() {
  const [code, setCode] = useState("");
  useEffect(() => {
    getCode("/watermark/代码.txt").then(({ data }) => {
      setCode(data);
    });
  }, []);

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const onChange: UploadProps["onChange"] = async ({
    fileList: newFileList,
  }) => {
    if (newFileList.length > 0) {
      const file: any = await addWatermark(newFileList[0].originFileObj);
      const newFile = [{ ...newFileList[0], originFileObj: file }];
      setFileList(newFile);
    } else {
      setFileList(newFileList);
    }
  };
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as FileType);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  return (
    <>
      <FirstTitle title="图片添加水印" />
      <EffectContainer
        effect={
          <Upload
            action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
            listType="picture-card"
            fileList={fileList}
            onChange={onChange}
            onPreview={onPreview}
          >
            {fileList.length < 1 && "+ Upload"}
          </Upload>
        }
        code={<Code content={code} />}
      />
    </>
  );
}

export default WaterMark;
